package api

import (
	"net/http"
	"playbook/ginsvr/src/orm"
	"playbook/ginsvr/src/orm/subprocess"
	"playbook/ginsvr/src/parsejson"
	"playbook/ginsvr/src/source/gene"
	"playbook/ginsvr/src/utils/fileutil"
	"playbook/ginsvr/src/utils/fileutil/watcher"
	"playbook/ginsvr/src/utils/httputil"

	"github.com/gin-gonic/gin"
)

//r.POST("copySubProcess", api.CopySubProcess)
func CopySubProcess(c *gin.Context) {

	var param map[string]interface{}
	if c.Bind(&param) == nil {
		resp := subprocess.CopySubProcess(param)
		c.JSON(http.StatusOK, resp)
	}
}

//r.POST("scriptcopy", api.Scriptcopy)
func Scriptcopy(c *gin.Context) {
	var content httputil.CopyContent
	var resp orm.Response

	if c.Bind(&content) == nil {

		fileutil.CopyFile(content.Newpath[0], content.Oldpath[0])
		fileutil.CopyFile(content.Newpath[1], content.Oldpath[1])
		watcher.AddWatchFile(content.Newpath[0], content.IP)
		watcher.AddWatchFile(content.Newpath[1], content.IP)
	}

	resp.RespCode = "000000"
	resp.RespMsg = "script local delete succcess!"
	c.JSON(http.StatusOK, resp)
}

//r.POST("saveSubProcess", api.SaveSubProcess)
func SaveSubProcess(c *gin.Context) {

	var savedata parsejson.Cells
	if c.Bind(&savedata) == nil {

		var resp orm.Response

		pro := parsejson.SaveSubProcess(savedata.Cells).(map[string]interface{})
		if pro["respCode"] == "000001" || pro["respCode"] == "000003" {
			c.JSON(http.StatusOK, pro)
			return
		}

		genebeanlist := []orm.GenebeanParammsg{}
		if pro["genebeanmsgList"] != nil {
			genebeanlist = pro["genebeanmsgList"].([]orm.GenebeanParammsg)
		}

		for _, genebeanmsg := range genebeanlist {
			if genebeanmsg.Inparamid != "" {
				gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Inparamid, genebeanmsg.Subpath)
			}
			if genebeanmsg.Outparamid != "" {
				gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Outparamid, genebeanmsg.Subpath)
			}

		}

		resp.RespCode = "000000"
		resp.RespMsg = "process save success!"
		c.JSON(http.StatusOK, resp)
	}
}
